/*
 * To change this template, choose Tools | Templates and open the template in
 * the editor.
 */
package br.jm.acionista.converter;

import br.jm.acionista.base.eao.EaoException;
import br.jm.acionista.entity.TipoTransferencia;
import br.jm.acionista.sistema.eao.TipoTransferenciaEao;
import br.jm.acionista.view.TipoTransferenciaBean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;

/**
 *
 * @author joao
 */
public class TipoConverter implements Converter {

    private List<TipoTransferencia> tipoTransferenciaList;
    private TipoTransferencia tipoTransferencia;
    private TipoTransferenciaEao TipoTransferenciaJpa;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        TipoTransferenciaJpa = TipoTransferenciaEao.getInstance();
        tipoTransferencia = new TipoTransferencia();
        tipoTransferenciaList = new ArrayList<TipoTransferencia>();

        if (value.trim().equals("") || value.equals("null")) {
            return null;
        } else {
            try {
                Map<String, String> pesquisas = new HashMap<String, String>();
                pesquisas.put("dscTipo", value);
                try {
                    tipoTransferenciaList = TipoTransferenciaJpa.getNative("TipoTransferencia", 0, 5, "dscTipo", true, pesquisas, null);
                } catch (EaoException ex) {
                    Logger.getLogger(TipoTransferenciaBean.class.getName()).log(Level.SEVERE, null, ex);
                }

                if (!tipoTransferenciaList.isEmpty()) {
                    tipoTransferencia = tipoTransferenciaList.get(0);
                }

                return tipoTransferencia;
            } catch (Exception exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Departamento"));
            }
        }
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((TipoTransferencia) value).getIdTipo());
        }
    }
    
}
